在Python中手动引发(抛出)异常 | 您所在的位置:网站首页 › python throw语句 › 在Python中手动引发(抛出)异常 |
如何在Python中引发异常,以便以后可以通过except块捕获该异常? #1楼不要这样做 。 引发一个绝对的Exception绝对不是正确的选择。 请参阅亚伦·霍尔(Aaron Hall)的出色答案 。 不能得到比这更多的pythonic: raise Exception("I know python!")如果您需要更多信息,请参阅python 的凸起语句文档 。 #2楼 如何在Python中手动引发/引发异常?使用在语义上适合您的问题的最特定的Exception构造函数 。 在您的消息中要具体,例如: raise ValueError('A very specific bad thing happened.') 不要引发通用异常避免引发通用异常。 要捕获它,您必须捕获将其子类化的所有其他更具体的异常。 问题1:隐藏错误 raise Exception('I know Python!') # Don't! If you catch, likely to hide bugs.例如: def demo_bad_catch(): try: raise ValueError('Represents a hidden bug, do not catch this') raise Exception('This is the exception you expect to handle') except Exception as error: print('Caught this error: ' + repr(error)) >>> demo_bad_catch() Caught this error: ValueError('Represents a hidden bug, do not catch this',) 问题2:无法抓住而更具体的捕获不会捕获一般异常: def demo_no_catch(): try: raise Exception('general exceptions not caught by specific handling') except ValueError as e: print('we will not catch exception: Exception') >>> demo_no_catch() Traceback (most recent call last): File "", line 1, in File "", line 3, in demo_no_catch Exception: general exceptions not caught by specific handling 最佳做法: raise声明而是使用在语义上适合您的issue的最特定的Exception构造函数 。 raise ValueError('A very specific bad thing happened')这也方便地允许将任意数量的参数传递给构造函数: raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')这些参数由Exception对象上的args属性访问。 例如: try: some_code_that_may_raise_our_value_error() except ValueError as err: print(err.args)版画 ('message', 'foo', 'bar', 'baz')在Python 2.5中,实际的message属性已添加到BaseException中,以鼓励用户继承Exceptions的子类并停止使用args ,但是message的引入和args的原始弃用已被收回 。 最佳做法: except子句例如,在except子句中时,您可能想要记录发生了特定类型的错误,然后重新引发。 保留堆栈跟踪时执行此操作的最佳方法是使用裸机抬高语句。 例如: logger = logging.getLogger(__name__) try: do_something_in_app_that_breaks_easily() except AppError as error: logger.error(error) raise # just this! # raise AppError # Don't do this, you'll lose the stack trace! 不要修改您的错误...但是如果您坚持的话。您可以使用sys.exc_info()来保留stacktrace(和错误值),但这是更容易出错的方式,并且在Python 2和3之间存在兼容性问题 ,建议您使用裸raise来重新筹集资金。 解释一下sys.exc_info()返回类型,值和回溯。 type, value, traceback = sys.exc_info()这是Python 2中的语法-请注意,这与Python 3不兼容: raise AppError, error, sys.exc_info()[2] # avoid this. # Equivalently, as error *is* the second object: raise sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2]如果愿意,您可以修改新加薪时发生的情况-例如,为实例设置新的参数: def error(): raise ValueError('oops!') def catch_error_modify_message(): try: error() except ValueError: error_type, error_instance, traceback = sys.exc_info() error_instance.args = (error_instance.args[0] + ' ',) raise error_type, error_instance, traceback并且我们在修改args时保留了整个回溯。 请注意,这不是最佳做法,并且在Python 3中是无效的语法 (使得保持兼容性变得更加困难)。 >>> catch_error_modify_message() Traceback (most recent call last): File "", line 1, in File "", line 3, in catch_error_modify_message File "", line 2, in error ValueError: oops!在Python 3中 : raise error.with_traceback(sys.exc_info()[2])同样:避免手动操作回溯。 它效率较低 ,更容易出错。 而且,如果您使用线程和sys.exc_info您甚至可能会得到错误的回溯(尤其是如果您对控制流使用异常处理,我个人倾向于避免这种情况。) Python 3,异常链接在Python 3中,您可以链接异常,以保留回溯: raise RuntimeError('specific message') from error意识到: 这确实允许更改引发的错误类型,并且 这与Python 2 不兼容。 不推荐使用的方法:这些可以轻松隐藏甚至进入生产代码。 您想提出一个例外,而这样做会引发一个例外, 但不是原计划! 在Python 2中有效,但在Python 3中无效 : raise ValueError, 'message' # Don't do this, it's deprecated!仅在更旧的Python版本 (2.4及更低版本 )中有效,您仍然可以看到有人在引发字符串: raise 'message' # really really wrong. don't do this.在所有现代版本中,这实际上会引发TypeError,因为您没有引发BaseException类型。 如果您没有检查正确的例外情况,并且没有知道该问题的审阅者,那么它可能会投入生产。 用法示例我提出异常以警告使用者如果我的API使用不正确: def api_func(foo): '''foo should be either 'baz' or 'bar'. returns something very useful.''' if foo not in _ALLOWED_ARGS: raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo))) 适当时创建自己的错误类型“我想故意犯一个错误,以便将其排除在外” 您可以创建自己的错误类型,如果要指示应用程序存在某些特定的错误,只需将异常层次结构中的适当点子类化: class MyAppLookupError(LookupError): '''raise this when there's a lookup error for my app'''和用法: if important_key not in resource_dict and not ok_to_be_missing: raise MyAppLookupError('resource is missing, and that is not ok.') #3楼对于常见的情况,您需要针对某些意外情况抛出异常,并且您从不打算抓住它,而只是快速失败以使您能够从那里进行调试(如果发生的话)—最合乎逻辑的是AssertionError : if 0 < distance Error I have raised an Exception #raise execption try: raise ValueError except ValueError as exp: print ("Error", exp) # Output -> Error3.提高 没有任何参数的raise语句将重新引发最后一个异常。 如果您需要在捕获异常之后执行一些操作然后重新引发它,这将很有用。 但是,如果以前没有异常,则raise语句引发TypeError Exception。 def somefunction(): print("some cleaning") a=10 b=0 result=None try: result=a/b print(result) except Exception: #Output -> somefunction() #some cleaning raise #Traceback (most recent call last): #File "python", line 8, in #ZeroDivisionError: division by zero4.从original_exception引发异常(参数) 此语句用于创建异常链接,其中响应另一个异常而引发的异常可以包含原始异常的详细信息-如下例所示。 class MyCustomException(Exception): pass a=10 b=0 reuslt=None try: try: result=a/b except ZeroDivisionError as exp: print("ZeroDivisionError -- ",exp) raise MyCustomException("Zero Division ") from exp except MyCustomException as exp: print("MyException",exp) print(exp.__cause__)输出: ZeroDivisionError -- division by zero MyException Zero Division division by zero #5楼首先阅读现有的答案,这只是一个附录。 请注意,可以带或不带参数引发异常。 例: raise SystemExit退出程序,但是您可能想知道发生了什么。因此可以使用它。 raise SystemExit("program exited")这将在关闭程序之前将“程序退出”打印到stderr。 #6楼只是要注意:有时候您确实想处理通用异常。 如果要处理大量文件并记录错误,则可能要捕获文件发生的任何错误,将其记录下来,然后继续处理其余文件。 在这种情况下, try: foo() except Exception as e: print(str(e)) # Print out handled error阻止这样做的好方法。 您仍将要raise特定的异常,以便您了解异常的含义。 #7楼抛出异常的另一种方法是assert 。 您可以使用assert来验证是否满足条件,否则将引发AssertionError 。 有关更多详细信息,请在此处查看 。 def avg(marks): assert len(marks) != 0,"List is empty." return sum(marks)/len(marks) mark2 = [55,88,78,90,79] print("Average of mark2:",avg(mark2)) mark1 = [] print("Average of mark1:",avg(mark1)) |
CopyRight 2018-2019 实验室设备网 版权所有 |